package io.gitee.geminidev.bot.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import io.gitee.geminidev.bot.BotContext;
import io.gitee.geminidev.bot.domain.MessageResponse;
import io.gitee.geminidev.bot.type.Status;

import java.util.Map;

/**
 * @Author gemini
 * @Date 2023/4/5 12:37
 * @description:
 */
public class MessageHttpApi implements MessageApi {

    private BotContext context;

    public void setContext(BotContext context) {
        this.context = context;
    }

    @Override
    public Status sendMessage(String channelId, MessageResponse params) {
        if(params.getFileImage() != null){
            return sendFormMessage(channelId, params);
        } else {
            return sendJsonMessage(channelId, params);
        }
    }

    private Status sendJsonMessage(String channelId, MessageResponse params){
        HttpResponse execute = HttpUtil.createPost(context.getHttpUri() + String.format("/channels/%s/messages", channelId))
                .header("Authorization", context.getToken())
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonStr(BeanUtil.beanToMap(params, true, true)))
                .execute();
        JSONObject entries = JSONUtil.parseObj(execute.body());
        return parseStatus(entries);
    }

    private Status sendFormMessage(String channelId, MessageResponse params) {
        Map<String, Object> form = BeanUtil.beanToMap(params, true, true);
        HttpResponse execute = HttpUtil.createPost(context.getHttpUri() + String.format("/channels/%s/messages", channelId))
                .header("Authorization", context.getToken())
                .form(form).execute();
        JSONObject entries = JSONUtil.parseObj(execute.body());
        return parseStatus(entries);
    }

    private Status parseStatus(JSONObject entries){
        switch (entries.getInt("code")){
            case 304023:
            case 304024:
                return Status.SUCCESS;
            default:
                StaticLog.warn("消息发送失败: " + JSONUtil.toJsonStr(entries));
                return Status.FAILD;
        }
    }
}
